function [ FS,E ] = SA( FS,Tk,train_t_input,train_v_input,train_t_target,train_v_target, algorithm0 )
%SA Simulated Anealing
%   Detailed explanation goes here
%  FS:Feature subset
%  Tk:Total run time for SA
%  train_t_input��training dataset
%  train_v_input:Validation dataset
%  train_t_target:Training label
%  train_v_target:Validation label

%Output
%  FS:Feature subset
%  E:Fitness of the feature individuals

Tc = Tk;
u_target = train_t_target;
v_target = train_v_target;

[N,M] = size(FS);
E=zeros(N,1);

for i=1:N
    if Tc>0
        t1 = clock;
        feasub = FS(i,:);
        din = find(feasub);
        u = train_t_input(:,din);
        v = train_v_input(:,din);
        
%         [Prior,PriorN,Cond,CondN]=MLKNN_train(u,u_target',10,1);
%         [HammingLoss,RankingLoss,OneError,Coverage,Average_Precision,Outputs,Pre_Labels]=MLKNN_test(u,u_target',v,v_target',10,Prior,PriorN,Cond,CondN);
%         E(i) = Average_Precision;
        algorithm0.build(u, u_target);
        result_i = algorithm0.apply(u, u_target);
        E(i) = AveragePrecision.calc(u_target, result_i.Y_hat);
        
        t2 = clock;
        Tspent = etime(t2,t1) ;
        Tc = Tc-Tspent;
    else
        break
    end
end

while Tc > 0
    for i=1:N
        if Tc>0
            t1 = clock;
            L = Tk/log2(0.5);
            pm = 0.5-0.5*exp(Tc/L);
            feasub = FS(i,:);
            [feasub] = mutation(feasub,pm);
            
            din = find(feasub);
            u = train_t_input(:,din);
            v = train_v_input(:,din);
            
%             [Prior,PriorN,Cond,CondN]=MLKNN_train(u,u_target',10,1);
%             [HammingLoss,RankingLoss,OneError,Coverage,Average_Precision,Outputs,Pre_Labels]=MLKNN_test(u,u_target',v,v_target',10,Prior,PriorN,Cond,CondN);
%             EM = Average_Precision;
            algorithm0.build(u, u_target);
            result_i = algorithm0.apply(u, u_target);
            EM = AveragePrecision.calc(u_target, result_i.Y_hat);
            
            if  EM > E(i)
                FS(i,:) = feasub;
                E(i) = EM;
            else if exp(-(E(i)-EM)/Tc)<rand
                    FS(i,:) = feasub;
                    E(i) = EM;
                end
            end
            t2 = clock;
            Tspent = etime(t2,t1) ;
            Tc = Tc-Tspent;
        else
            break
        end
    end%for
end%while

end
